
#include "sample.h"
#include "adc.h"
#include "queue.h"

#define SAMPLE_BUFFER_SIZE 1

TaskHandle_t g_sample_task_handle       = NULL;
TaskHandle_t g_sample_parse_task_handle = NULL;

uint32_t g_sample_buffer_A[SAMPLE_BUFFER_SIZE];
uint32_t g_sample_buffer_B[SAMPLE_BUFFER_SIZE];

// Buffer state enum for better readability
typedef enum {
    BUFFER_INIT = 0,
    BUFFER_A = 1,
    BUFFER_B = 2
} BufferState;

void Sample_Task(void *argument)
{
  BufferState currentBuffer = BUFFER_INIT;
  uint32_t data;

  log_i("Start Sample Data in buffer A(%p)", g_sample_buffer_A);
  HAL_ADC_Start_DMA(&hadc1, g_sample_buffer_A, SAMPLE_BUFFER_SIZE);
  currentBuffer = BUFFER_A;

  for(;;)
  {
		// log_i("Sample_Task is Running!");
    if ( pdPASS == xTaskNotifyWait(0, 0, &data, portMAX_DELAY) )
    {
      switch (currentBuffer)
      {
        case BUFFER_A:
        {
          log_i("Sample Data in buffer B(%p)", g_sample_buffer_B);
          HAL_ADC_Start_DMA(&hadc1, g_sample_buffer_B, SAMPLE_BUFFER_SIZE);
          xTaskNotify(g_sample_parse_task_handle, (uint32_t)g_sample_buffer_A, eSetValueWithoutOverwrite);
          currentBuffer = BUFFER_B;
          break;
        }
        case BUFFER_B:
        {
          log_i("Sample Data in buffer A(%p)", g_sample_buffer_A);
          HAL_ADC_Start_DMA(&hadc1, g_sample_buffer_A, SAMPLE_BUFFER_SIZE);
          xTaskNotify(g_sample_parse_task_handle, (uint32_t)g_sample_buffer_B, eSetValueWithoutOverwrite);
          currentBuffer = BUFFER_A;
          break;
        }
        default:
          break;
      }
    }
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

void Sample_Parse_Task(void *argument)
{
  uint32_t *buf  = NULL;
  double voltage = 0.0;
  for(;;)
  {
		// log_i("Sample_Parse_Task is Running!");
    if ( pdTRUE == xTaskNotifyWait(0, 0, (uint32_t *)&buf, portMAX_DELAY) )
		{
      voltage = (double)buf[0] * 3300 / 4096;

			log_i( "Parse Data in buffer(%p) = %.2fmV", buf,  voltage);
      log_e("--------------------------------------------------");
		}
  }
}


Sample_ADC_Callback
{
  BaseType_t pxHigherPriorityTaskWoken = pdFALSE;

  log_i("Sample done");
  vTaskNotifyGiveFromISR(g_sample_task_handle, &pxHigherPriorityTaskWoken);

  if (pxHigherPriorityTaskWoken)
  {
    portYIELD_FROM_ISR(pxHigherPriorityTaskWoken);
  }
  HAL_GPIO_TogglePin(BLUE_LED_GPIO_Port, BLUE_LED_Pin);
}
